package com.cq.androidtools.jetpack.paging3

import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.cq.base.retrofit.a.Retrofit2

/**
 * 作者: CQ
 * 日期: 2021-07-06
 * 说明: 新建一个 RepoPagingSource 继承自 PagingSource
 */
class RepoPagingSource : PagingSource<Int, Repo>() {
    override fun getRefreshKey(state: PagingState<Int, Repo>): Int? = null

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Repo> {
        return try {
            val page = params.key?:1
            val pageSize = params.loadSize
            val repoResponse = Retrofit2.getInstance("https://api.github.com/").getService<GitHubService>().searchRepos(page, pageSize)
            val repoItems = repoResponse.items
            val prevKey = if (page > 1) page - 1 else null
            val nextKey = if (repoItems.isNotEmpty()) page + 1 else null
            LoadResult.Page(repoItems, prevKey, nextKey)
        } catch (e : Exception) {
            e.printStackTrace()
            LoadResult.Error(e)
        }
    }
}